<script lang="ts" setup>
import type { LicenseListItem } from '@/apis/model/License'
import { getCertRecordListApi } from '@/apis/modules/cert'
import {
  certManualApplyOptions,
  certRecordStatusOptions,
  LicenseSourceOptions,
} from '@/constants/cdn-node'

import router from '@/router'
import { commonTableProps } from '@/utils/table'
import ApplyLog from '../../cert-detail/dialogs/ApplyLog.vue'
// import { getLog } from './state'
import useConfig from './useConfig'

const { tableColumns, searchSchema } = useConfig()

const queryParams = ref({
  // created_at_gte: '',
  // created_at_lte: '',
  app_id: '',
})

// const { visible } = usePopup()
const { visible: logVisible, open: openLog, data: logData } = usePopup()
// const {
//   visible: detailVisible,
//   open: openDetail,
//   data: detailData,
// } = usePopup()

// const { filterSchemes, columns } = useTableColumn()
const appList = computed<OptionItem[]>(() => {
  return useAppStore().appList || []
})
const { data, loading, run, pagination } = useListRequest(
  getCertRecordListApi,
  {
    params: queryParams,
    immediate: true,
  },
)
const { createSortChange } = useTable(run, data)

const onSorterChange = createSortChange(queryParams)
// 刷新当前行数据
function handleRefreshRow(row: LicenseListItem) {
  if (row.id)
    deleteUrlParams()
  data.value.forEach((item) => {
    if (item.id !== row.id)
      return
    Object.assign(item, row)
  })
}
function deleteUrlParams() {
  // 获取当前路由的完整路径
  const currentPath = router.currentRoute.value.fullPath
  // 检查是否有查询参数
  const queryStringIndex = currentPath.indexOf('?')
  // 如果没有查询参数，则无需做任何操作
  if (queryStringIndex === -1)
    return
  // 获取路径部分
  let path = currentPath.slice(0, queryStringIndex)
  // 如果path后缀是/，则去掉
  if (path.endsWith('/')) {
    path = path.slice(0, -1)
  }
  // 构建新的 URL（没有查询参数）
  const newPath = path
  // 使用 replace 方法更新 URL，不添加新的历史记录条目
  router.replace(newPath)
}
async function handleOpenLog(record: LicenseListItem) {
  // const res = await getSwitcherListApi(record.id!)
  openLog(record)
  // if (res)
  //   openLog(record)
}
// 跳转到站点详情
// function goToSite(row: LicenseListItem) {
//   loading.value = true
//   getSwitcherListApi({ id: row.site_id })
//     .then((res) => {
//       // useSiteStore().setSiteInfo(res)
//       router.push({
//         name: 'LicenseAgreement',
//         params: { id: row.site_id },
//       })
//     })
//     .finally(() => {
//       loading.value = false
//     })
// }

function FirstDomain(domains: string) {
  if (!domains || domains.trim() === '') {
    return { domain: null, length: 0 }
  }
  const parts = domains.split(',')
  const domain = parts[0] || ''
  const length = parts.length - 1
  return { domain, length }
}
onMounted(() => {
  // const id = getQueryParameter('id') as string
  // const site_domain = getQueryParameter('domain') as string
  // if (id) {
  //   handleOpenLog({
  //     id,
  //     site_domain,
  //   })
  // }
})

const dateRange = ref<string[]>([])
watch(dateRange, () => {
  const [start, end] = dateRange.value || []
  queryParams.value.created_at_gte = start || ''
  queryParams.value.created_at_lte = end ? (Number(end) + 86400).toString() : ''
  run()
})
</script>

<template>
  <main-container
    :loading="loading"
    :pagination="pagination"
    @run="run"
  >
    <div class="mb-4 flex justify-between">
      <!-- <a-range-picker
        v-model="dateRange"
        show-time
        value-format="X"
        :placeholder="['选择开始时间', '选择结束时间']"
        class="w-100!"
      >
        <template #suffix-icon>
          <i-icons-calendar class="mt-1" />
        </template>
      </a-range-picker> -->
      <a-select
        v-model="queryParams.app_id"
        :options="[{ label: '全部应用', value: '' }, ...appList]"
        placeholder="请选择所属应用"
        class="mr-4 !w-[136px]"
        @change="run"
      />
      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        @search="run"
      />
      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="loading"
        @click="run"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': loading }" />
        </template>
      </a-button>
    </div>
    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="data"
      @sorter-change="onSorterChange"
    >
      <template #domain="{ record }">
        <div class="flex items-center">
          <span
            style="
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >{{ FirstDomain(record.domain).domain || '-' }}</span>
          <div
            v-if="FirstDomain(record.domain).length > 0"
            class="domains-length-tag"
          >
            {{ FirstDomain(record.domain).length }}
          </div>
        </div>
      </template>
      <template #appId="{ record }">
        <div>
          <span>{{ getOptionsLabel(appList, record.app_id) }}</span>
        </div>
      </template>
      <template #trigger_source="{ record }">
        <div>
          <span>{{
            getOptionsLabel(certManualApplyOptions, record.trigger_source)
          }}</span>
        </div>
      </template>
      <template #source="{ record }">
        <span>{{ getOptionsLabel(LicenseSourceOptions, record.source) }}</span>
      </template>
      <template #brand="{ record }">
        {{ record.brand || '-' }}
      </template>
      <template #status="{ record }">
        <div>
          <span
            :class="
              record?.status === 1
                ? 'text-#86909C'
                : record?.status === 2
                  ? 'text-#FA5566'
                  : 'text-#00A65B'
            "
          >{{
            getOptionsLabel(certRecordStatusOptions, record?.status)
          }}</span>
        </div>
      </template>
      <template #acme="{ record }">
        <text-ell :content="record.acme" />
      </template>
      <template #actions="{ record }">
        <!-- <a-link :hoverable="false" :disabled="record.apply_result !== 1" @click="openDetail(record)">
          证书详情
        </a-link> -->
        <a-link
          :hoverable="false"
          @click="handleOpenLog(record)"
        >
          <i-icons-log size="16px" />
        </a-link>
      </template>
    </a-table>
    <apply-log
      v-model:visible="logVisible"
      v-model:record="logData"
      @refresh-row="row => handleRefreshRow(row)"
    />
  </main-container>
</template>

<style lang="less" scoped>
.arco-table-tr:hover .table-link-text {
  color: #165dff;
}

.domains-length-tag {
  color: var(--text-2, #4e5969);

  /* regular/12 */
  font-family: 'Microsoft YaHei UI';
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  display: flex;
  height: 16px;
  padding: 0px 6px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
  border-radius: 9999px;
  border: 1px solid var(--border-2, #e5e6eb);
  background: var(--fill-1, #f7f8fa);
  margin-left: 4px;
}
</style>
